package com.mamesoft.namibiamc.tools;

import com.Ostermiller.util.RandPass;
import java.io.*;
import java.sql.SQLException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.Security;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.ResultSet;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;

public class Utility {

    public final static int LONGITUDINE = 0;
    public final static int LATITUDINE = 1;

    public static List fetchCoordinate(String luogoNascita) {
        ArrayList<String> coo = new ArrayList<String>();
        try {
            luogoNascita = luogoNascita.replace(" ", "%20");
            String xml = fetchXML(luogoNascita);
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            StringReader reader = new StringReader(xml);
            InputSource is = new InputSource(reader);
            Document doc = db.parse(is);
            Element rootElement = doc.getDocumentElement();
            rootElement.normalize();
            XPathFactory factory = XPathFactory.newInstance();
            XPath xpath = factory.newXPath();

            XPathExpression exp = xpath.compile("/geonames/geoname/lat");
            NodeList nodes = (NodeList) exp.evaluate(doc, XPathConstants.NODESET);
            String latitudine = nodes.item(0).getTextContent();

            exp = xpath.compile("/geonames/geoname/lng");
            nodes = (NodeList) exp.evaluate(doc, XPathConstants.NODESET);
            String longitudine = nodes.item(0).getTextContent();
            coo.add(longitudine);
            coo.add(latitudine);
            return coo;
        } catch (Exception ex) {
            return null;
        }
    }

    public static String toPDF(String idMedico, String data, String anamnesi, String paziente)
            throws DocumentException, FileNotFoundException, BadElementException,
            MalformedURLException, IOException, SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException {

        String webRoot = ((ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext()).getRealPath("/");
        String contextPath = ((ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext()).getContextPath();
        com.itextpdf.text.Document document = new com.itextpdf.text.Document();

        RandPass r = new RandPass(new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'});
        String file = r.getPass(16);
        file += ".pdf";

        PdfWriter.getInstance(document, new FileOutputStream(webRoot + "PDF/" + file));

        document.open();

        document.newPage();

        Paragraph header = new Paragraph();
        Image logo = new Image(Image.getInstance(webRoot + "images/head.jpg")) {
        };
        logo.scalePercent(52);
        header.add(logo);
        header.add("\n\n\n\n");
        document.add(header);

        String q = "SELECT nome,cognome FROM anagrafe WHERE id='" + idMedico + "'";
        Connection c = JDBC.connect();
        ResultSet set = JDBC.executeQuery(q, c);
        String nomeMedico = "";
        if (set.next()){
            nomeMedico = set.getString("nome")+" "+set.getString("cognome");
        }
        
        Paragraph p1 = new Paragraph("Il medico "+nomeMedico+" numero di matricola " + idMedico + " dichiara che in data "
                + data + " è stata svolta la visita a " + paziente + " con la seguente anamnesi: \n", FontFactory.getFont(FontFactory.HELVETICA, 10));


        p1.add(anamnesi + "\n\n");
        document.add(p1);

        Paragraph p2 = new Paragraph("", FontFactory.getFont(FontFactory.HELVETICA, 10));
        p2.setAlignment(Paragraph.ALIGN_BOTTOM);



        p2.add("\n\n\n\n\n\n\n\n\n\nIl Suo medico di fiducia");
        document.add(p2);
        document.close();
        return "http://localhost:8084"+contextPath + "/PDF/" + file;
    }

    public static void sendEmail(String mail, String link) throws MessagingException {
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
        // Get a Properties object
        Properties props = System.getProperties();
        props.setProperty("mail.smtp.host", "smtp.gmail.com");
        props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.port", "465");
        props.setProperty("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.auth", "true");
        props.put("mail.debug", "false");
        final String user = "namibiamc@gmail.com";
        final String password = "muccamucca";
        Session session = Session.getDefaultInstance(props, new Authenticator() {

            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(user, password);
            }
        });
        // — Create a new message –
        Message msg = new MimeMessage(session);
        // — Set the FROM and TO fields – 
        msg.setFrom(new InternetAddress(user + ""));
        msg.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse("simone.melchiori90@gmail.com", false));
        msg.setSubject("Namibia Medical Control: Link referto visita");
        msg.setText("email:" + mail + "\n\n\n\nCaro/a " + mail + "\n \n La informiamo che è disponibile il PDF "
                + "contenente le informazioni relative all'ultima visita.\n"
                + "Il link è il seguente:" + link
                + "\n\n"
                + "Distinti Saluti \n"
                + "Il team di NMC");
        msg.setSentDate(new Date());
        Transport.send(msg);
    }

    private static String fetchXML(String luogoNascita) throws MalformedURLException, IOException {
        URL url = new URL("http://ws.geonames.org/search?q=" + luogoNascita);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        if (conn.getResponseCode() != 200) {
            throw new IOException(conn.getResponseMessage());
        }
// Buffer the result into a string
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = rd.readLine()) != null) {
            sb.append(line);
        }
        rd.close();
        conn.disconnect();
        return sb.toString();
    }

    public static boolean isValidEmail(String email) {

        //Set the email pattern string
        Pattern p = Pattern.compile(".+@.+\\.[a-z]+");

        //Match the given string with the pattern
        Matcher m = p.matcher(email);

        //check whether match is found 
        return m.matches();
    }

    public static byte[] getBytesFromFile(File file) throws IOException {
        InputStream is = new FileInputStream(file);

        // Get the size of the file
        long length = file.length();

        if (length > Integer.MAX_VALUE) {
            // File is too large
        }

        // Create the byte array to hold the data
        byte[] bytes = new byte[(int) length];

        // Read in the bytes
        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length
                && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
            offset += numRead;
        }

        // Ensure all the bytes have been read in
        if (offset < bytes.length) {
            throw new IOException("Could not completely read file " + file.getName());
        }

        // Close the input stream and return bytes
        is.close();
        return bytes;
    }

    public static void copyfile(String srFile, String dtFile) {
        try {
            File f1 = new File(srFile);
            File f2 = new File(dtFile);
            InputStream in = new FileInputStream(f1);

            //For Append the file.
//  OutputStream out = new FileOutputStream(f2,true);

            //For Overwrite the file.
            OutputStream out = new FileOutputStream(f2);

            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
        } catch (FileNotFoundException ex) {
            System.exit(0);
        } catch (IOException e) {
        }
    }
}